import axios from 'axios'
import router from '../router'
// import store from '../store'
// import { MessageBox } from 'element-ui'
// import store from '../store'

axios.interceptors.request.use(
  config => {
    // 登录页面不加token
    if (router.history.current.name !== 'login') {
      if (localStorage.getItem('userInfo')) { // 判断是否存在token，如果存在的话，则每个http header都加上token
        config.headers.token = JSON.parse(localStorage.getItem('userInfo')).token
      }
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  undefined,
  error => {
    let res = error.response
    switch (res.status) {
      case 401:
        // 返回 401 清除token信息并跳转到登录页面
        // store.commit(types.LOGOUT);
        // router.replace({
        //  path: '/login',
        //  query: {redirect: router.currentRoute.fullPath}
        // })
        console.log('未登录 或者token过期')
        break
      case 403:
        console.log('您没有该操作权限')
        break
      // alert('您没有该操作权限');
      case 500:
      // MessageBox(store.state.aginLogin + '!', store.state.tips, {
      //   confirmButtonText: store.state.detemine,
      //   cancelButtonText: '',
      //   type: 'warning'
      // }).then(() => {
      //   localStorage.removeItem('userInfo')
      //   router.replace({
      //     path: '/login',
      //     query: {redirect: router.currentRoute.fullPath}
      //   })
      // })
    }
    return Promise.reject(error.response.data) // 返回接口返回的错误信息
  })

const http = (url, params) => {
  return new Promise((resolve, reject) => {
    axios.post(url, params, {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    }).then(response => {
      resolve(response.data)
    }).catch(err => {
      reject(err)
    })
  })
}

export const getExcel = (url, params) => {
  return new Promise((resolve, reject) => {
    axios.post(url, params, {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      responseType: 'arraybuffer'
    }).then(response => {
      resolve(response.data)
    }).catch(err => {
      reject(err)
    })
  })
}

export const getHttp = url => {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    }).then(response => {
      resolve(response.data)
    }).catch(err => {
      reject(err)
    })
  })
}

export default http
